/**
 * 计时器兼容性检测和降级处理
 */

// 检测环境支持情况
export const checkCompatibility = () => {
  const support = {
    webWorker: typeof Worker !== 'undefined',
    serviceWorker: 'serviceWorker' in navigator,
    requestIdleCallback: 'requestIdleCallback' in window,
    requestAnimationFrame: 'requestAnimationFrame' in window,
    performance: 'performance' in window && 'now' in performance,
    pageVisibility: 'hidden' in document,
    userAgent: navigator.userAgent
  }

  // 检测是否为H5+ App环境
  support.isH5PlusApp = support.userAgent.includes('HBuilder') || 
                         support.userAgent.includes('uni-app') ||
                         support.userAgent.includes('DCloud') ||
                         typeof window.plus !== 'undefined'

  // 检测是否为移动设备
  support.isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(support.userAgent)

  // 检测浏览器类型
  if (support.userAgent.includes('Chrome')) {
    support.browser = 'Chrome'
  } else if (support.userAgent.includes('Firefox')) {
    support.browser = 'Firefox'
  } else if (support.userAgent.includes('Safari')) {
    support.browser = 'Safari'
  } else if (support.userAgent.includes('Edge')) {
    support.browser = 'Edge'
  } else {
    support.browser = 'Unknown'
  }

  return support
}

// 获取最佳计时策略
export const getBestTimerStrategy = () => {
  const support = checkCompatibility()
  
  if (support.webWorker) {
    return 'webWorker'
  } else if (support.requestAnimationFrame) {
    return 'requestAnimationFrame'
  } else if (support.requestIdleCallback) {
    return 'requestIdleCallback'
  } else {
    return 'setInterval'
  }
}

// 创建兼容的计时器
export const createCompatibleTimer = (strategy = null) => {
  const support = checkCompatibility()
  const selectedStrategy = strategy || getBestTimerStrategy()
  
  console.log(`使用计时策略: ${selectedStrategy}`)
  
  switch (selectedStrategy) {
    case 'webWorker':
      return createWebWorkerTimer()
    case 'requestAnimationFrame':
      return createRAFBasedTimer()
    case 'requestIdleCallback':
      return createRICBasedTimer()
    case 'setInterval':
    default:
      return createSetIntervalTimer()
  }
}

// Web Worker计时器（最佳选择）
function createWebWorkerTimer() {
  return {
    type: 'webWorker',
    isAvailable: () => true,
    start: (callback, interval = 1000) => {
      // 这里返回一个标识符，实际实现由WorkerManager处理
      return { type: 'webWorker', interval }
    },
    stop: (id) => {
      // 由WorkerManager处理
    },
    pause: (id) => {
      // 由WorkerManager处理
    },
    resume: (id) => {
      // 由WorkerManager处理
    }
  }
}

// 基于requestAnimationFrame的计时器
function createRAFBasedTimer() {
  let animationId = null
  let lastTime = 0
  let isRunning = false
  let interval = 1000
  
  const tick = (currentTime) => {
    if (!isRunning) return
    
    if (currentTime - lastTime >= interval) {
      lastTime = currentTime
      // 这里可以调用回调函数
    }
    
    animationId = requestAnimationFrame(tick)
  }
  
  return {
    type: 'requestAnimationFrame',
    isAvailable: () => typeof requestAnimationFrame !== 'undefined',
    start: (callback, timerInterval = 1000) => {
      if (isRunning) return null
      
      interval = timerInterval
      isRunning = true
      lastTime = performance.now()
      animationId = requestAnimationFrame(tick)
      
      return { type: 'requestAnimationFrame', id: animationId }
    },
    stop: (id) => {
      if (animationId) {
        cancelAnimationFrame(animationId)
        animationId = null
        isRunning = false
      }
    },
    pause: (id) => {
      isRunning = false
      if (animationId) {
        cancelAnimationFrame(animationId)
        animationId = null
      }
    },
    resume: (id) => {
      if (!isRunning) {
        isRunning = true
        lastTime = performance.now()
        animationId = requestAnimationFrame(tick)
      }
    }
  }
}

// 基于requestIdleCallback的计时器
function createRICBasedTimer() {
  let idleId = null
  let isRunning = false
  let interval = 1000
  let lastTime = 0
  
  const tick = (deadline) => {
    if (!isRunning) return
    
    const currentTime = Date.now()
    if (currentTime - lastTime >= interval) {
      lastTime = currentTime
      // 这里可以调用回调函数
    }
    
    if (deadline.timeRemaining() > 0) {
      idleId = requestIdleCallback(tick)
    } else {
      idleId = setTimeout(() => requestIdleCallback(tick), 1)
    }
  }
  
  return {
    type: 'requestIdleCallback',
    isAvailable: () => typeof requestIdleCallback !== 'undefined',
    start: (callback, timerInterval = 1000) => {
      if (isRunning) return null
      
      interval = timerInterval
      isRunning = true
      lastTime = Date.now()
      idleId = requestIdleCallback(tick)
      
      return { type: 'requestIdleCallback', id: idleId }
    },
    stop: (id) => {
      if (idleId) {
        if (typeof cancelIdleCallback !== 'undefined') {
          cancelIdleCallback(idleId)
        } else {
          clearTimeout(idleId)
        }
        idleId = null
        isRunning = false
      }
    },
    pause: (id) => {
      isRunning = false
      if (idleId) {
        if (typeof cancelIdleCallback !== 'undefined') {
          cancelIdleCallback(idleId)
        } else {
          clearTimeout(idleId)
        }
        idleId = null
      }
    },
    resume: (id) => {
      if (!isRunning) {
        isRunning = true
        lastTime = Date.now()
        idleId = requestIdleCallback(tick)
      }
    }
  }
}

// 基于setInterval的计时器（降级方案）
function createSetIntervalTimer() {
  let intervalId = null
  let isRunning = false
  
  return {
    type: 'setInterval',
    isAvailable: () => true,
    start: (callback, timerInterval = 1000) => {
      if (isRunning) return null
      
      isRunning = true
      intervalId = setInterval(callback, timerInterval)
      
      return { type: 'setInterval', id: intervalId }
    },
    stop: (id) => {
      if (intervalId) {
        clearInterval(intervalId)
        intervalId = null
        isRunning = false
      }
    },
    pause: (id) => {
      isRunning = false
      if (intervalId) {
        clearInterval(intervalId)
        intervalId = null
      }
    },
    resume: (id) => {
      if (!isRunning && intervalId) {
        isRunning = true
        // 注意：setInterval无法真正暂停，这里只是标记状态
      }
    }
  }
}

// 页面可见性检测
export const createVisibilityHandler = () => {
  if (!('hidden' in document)) {
    return {
      isVisible: () => true,
      onVisibilityChange: () => {},
      removeListener: () => {}
    }
  }
  
  let visibilityChangeHandler = null
  
  const isVisible = () => !document.hidden
  
  const onVisibilityChange = (callback) => {
    visibilityChangeHandler = callback
    document.addEventListener('visibilitychange', callback)
  }
  
  const removeListener = () => {
    if (visibilityChangeHandler) {
      document.removeEventListener('visibilitychange', visibilityChangeHandler)
      visibilityChangeHandler = null
    }
  }
  
  return {
    isVisible,
    onVisibilityChange,
    removeListener
  }
}

// 性能监控
export const createPerformanceMonitor = () => {
  if (!('performance' in window)) {
    return {
      getTime: () => Date.now(),
      mark: () => {},
      measure: () => {},
      getEntries: () => []
    }
  }
  
  return {
    getTime: () => performance.now(),
    mark: (name) => performance.mark(name),
    measure: (name, startMark, endMark) => performance.measure(name, startMark, endMark),
    getEntries: () => performance.getEntries()
  }
}

